package com.dongdongshop.controller;

import com.dongdongshop.domain.AjaxResult;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.SeckillService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("seckill")
public class SeckillController {

    @DubboReference
    private SeckillService seckillService;

    //秒杀商品同步预热
    @RequestMapping("hotPrepare")
    @ResponseBody
    public String hotPrepare() {
        seckillService.hotPrepare();
        return "秒杀商品同步成功";
    }
    //页面展示
    @RequestMapping("getSeckillList")
    @ResponseBody
    public AjaxResult getSeckillList(){
        try {
            List<TbSeckillGoods> seckillGoods =  seckillService.getSeckillList();
            return AjaxResult.OK().setData(seckillGoods);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }

    }


    //跳转抢购页面
    @RequestMapping("item")
    public String item(Long seckillId, Model model) {
        model.addAttribute("goods",seckillService.getSeckillById(seckillId));
        return "seckill-item";
    }

    //秒杀下单
    @RequestMapping("createOrder")
    @ResponseBody
    public AjaxResult createOrder(Long id){
        // 首先判断用户有没有登录
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            return AjaxResult.R(ResultEnum.TOLOGIN);
        }
        try {
            Long i = seckillService.createOrder(user.getId(),id);
            if (i < 0){
                return AjaxResult.R(ResultEnum.SALE_OVER);
            }
            return AjaxResult.OK().setData(String.valueOf(i));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    //获取订单id
    @RequestMapping("getOrderId")
    @ResponseBody
    public AjaxResult getOrderId(){
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            return AjaxResult.R(ResultEnum.TOLOGIN);
        }
        try {
            Long orderId = seckillService.getOrderId(user.getId());
            if (orderId == null){
                return AjaxResult.ERROR().setData("请去订单页面完成支付吧");
            }
            return AjaxResult.OK().setData(orderId.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }
}
